/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.services;

import com.google.inject.Inject;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.xptracker.domain.Domain;
import org.xptracker.domain.NamedSet;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.persistence.RollbackException;

import java.io.IOException;
import java.io.Reader;

public class AutoUpdater {
  private static final String RESOURCE_PREFIX = "org/xptracker/autoupdate/js/";

  private PersistenceManager persistenceManager;
  private UpdateProvider provider;
  private JsEngine jsEngine;

  @Inject
  public AutoUpdater(PersistenceManager persistenceManager, UpdateProvider provider, JsEngine jsEngine) {
    this.persistenceManager = persistenceManager;
    this.provider = provider;
    this.jsEngine = jsEngine;
  }

  public void execute() {
    jsEngine.withEngine(new EngineReceiver() {
      public void receive(final Context cx, final Scriptable scope) {
        persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
          public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
            scope.put("updater", scope, receiver);

            try {
              Domain domain = new Domain(persistenceManager);
              NamedSet appliedUpdates = domain.getNamedSet(receiver, "autoupdater");

              for (String filename : provider.listSetupFiles()) {
                execFile(filename, provider.loadSetupFile(filename), cx, scope);
                persistenceManager.flush();
              }

              for (String filename : provider.listUpdateFiles()) {
                if (!appliedUpdates.set.contains(filename)) {
                  execFile(filename, provider.loadUpdateFile(filename), cx, scope);
                  appliedUpdates.set.add(filename);
                }
              }
              receiver.update(appliedUpdates);
            } catch (Exception e) {
              throw new RollbackException(e);
            }
            return null;
          }
        });
      }
    });
  }

  private void execFile(String filename, Reader reader, Context cx, Scriptable scope) throws IOException {
    try {
      LogFactory.getLog(getClass()).info("Executing: " + filename);
      cx.evaluateReader(scope, reader, "<" + filename + ">", 1, null);
    } finally {
      reader.close();
    }
  }
}
